package com.doubao.device.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doubao.common.result.Result;
import com.doubao.device.dto.SmartDeviceDTO;
import com.doubao.device.entity.SmartDevice;
import com.doubao.device.entity.UserDeviceCollection;
import com.doubao.device.mapper.SmartDeviceMapper;
import com.doubao.device.mapper.UserDeviceCollectionMapper;
import com.doubao.device.service.UserDeviceCollectionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserDeviceCollectionServiceImpl implements UserDeviceCollectionService {

    private final UserDeviceCollectionMapper collectionMapper;
    private final SmartDeviceMapper deviceMapper; // 需要添加这个依赖

    @Override
    public Result<Void> collectDevice(Long userId, Long deviceId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }
        if (deviceId == null) {
            return Result.failed("智能体ID不能为空");
        }

        try {
            // 先检查是否已收藏
            int count = collectionMapper.checkIsCollected(userId, deviceId);
            if (count > 0) {
                return Result.success(null, "已经收藏过该智能体");
            }

            // 创建收藏记录
            UserDeviceCollection collection = new UserDeviceCollection();
            collection.setUserId(userId);
            collection.setDeviceId(deviceId);
            collectionMapper.insert(collection);

            // 增加智能体的收藏计数 - 使用deviceMapper
            int rows = deviceMapper.increaseCollectionCount(deviceId);
            if (rows <= 0) {
                log.warn("智能体收藏计数增加失败: deviceId={}", deviceId);
            }

            return Result.success(null, "收藏成功");
        } catch (Exception e) {
            log.error("收藏智能体失败", e);
            return Result.failed("收藏失败：" + e.getMessage());
        }
    }

    @Override
    public Result<Void> cancelCollection(Long userId, Long deviceId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }
        if (deviceId == null) {
            return Result.failed("智能体ID不能为空");
        }

        try {
            collectionMapper.deleteByUserIdAndDeviceId(userId, deviceId);

            return Result.success(null, "取消收藏成功");
        } catch (Exception e) {
            log.error("取消收藏失败", e);
            return Result.failed("取消收藏失败：" + e.getMessage());
        }
    }

    @Override
    public Result<Boolean> checkIsCollected(Long userId, Long deviceId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }
        if (deviceId == null) {
            return Result.failed("智能体ID不能为空");
        }

        try {
            int count = collectionMapper.checkIsCollected(userId, deviceId);
            return Result.success(count > 0);
        } catch (Exception e) {
            log.error("检查收藏状态失败", e);
            return Result.failed("检查收藏状态失败：" + e.getMessage());
        }
    }

    @Override
    public Result<IPage<SmartDeviceDTO>> getUserCollections(Long userId, Integer page, Integer size) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }

        try {
            log.info("获取用户ID {} 收藏的设备列表, 页码: {}, 大小: {}", userId, page, size);

            // 创建分页参数
            Page<SmartDevice> pageParam = new Page<>(page, size);

            // 使用优化的查询方法 - 直接联表查询所有需要的数据
            IPage<SmartDevice> devicePage = collectionMapper.selectUserCollectionsWithDetails(pageParam, userId);

            log.info("用户 {} 收藏列表查询结果: 总条数: {}, 总页数: {}",
                    userId, devicePage.getTotal(), devicePage.getPages());

            // 转换为DTO，处理额外信息
            IPage<SmartDeviceDTO> dtoPage = devicePage.convert(device -> {
                SmartDeviceDTO dto = new SmartDeviceDTO();
                BeanUtils.copyProperties(device, dto);

                // 标记为已收藏
                dto.setCollected(true);

                // 解析能力字段和知识库ID
                if (device.getAbilities() != null && !device.getAbilities().isEmpty()) {
                    dto.setAbilities(Arrays.asList(device.getAbilities().split(",")));
                }

                if (device.getKnowledgeBaseIds() != null && !device.getKnowledgeBaseIds().isEmpty()) {
                    try {
                        dto.setKnowledgeBaseIds(
                                Arrays.stream(device.getKnowledgeBaseIds().split(","))
                                        .map(Long::parseLong)
                                        .collect(Collectors.toList())
                        );
                    } catch (Exception e) {
                        log.warn("解析知识库IDs失败: {}", device.getKnowledgeBaseIds());
                    }
                }

                return dto;
            });

            return Result.success(dtoPage);
        } catch (Exception e) {
            log.error("获取用户收藏列表失败", e);
            return Result.failed("获取收藏列表失败: " + e.getMessage());
        }
    }
}